//
//  ViewController.m
//  btTest
//
//  Created by idiot.lin on 15/3/2.
//  Copyright (c) 2015年 biao.rao. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>


#import "CBluetoothManager.h"
#import "pullsdk.h"
#import "NSString+hexStringToData.h"
#import "NSData+dataTohexStr.h"
//static CBluetoothManager _blueManager;


@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) UILabel               *label;
@property (strong, nonatomic) CBCentralManager      *centralManager;
@property (strong, nonatomic) CBPeripheral          *connectPeripheral;
@property (nonatomic, strong) CBCharacteristic      *sendMessageCharacteristic;
@property (strong, nonatomic) NSMutableData         *data;

@property (nonatomic, strong) UITableView           *tableview;
@property (nonatomic, strong) NSMutableArray        *peripheralArr;
@property (nonatomic, strong) UILabel               *labelOfData;
@property (nonatomic, assign) CBluetoothManager     *blueManager;
@property (nonatomic, assign) void                  *handle;


@end


@implementation ViewController
@synthesize tableview,peripheralArr,labelOfData,connectPeripheral,handle;




- (void)viewDidLoad
{
    NSLog(@"DeviceIdentifier=======[%@]",[UIDevice currentDevice].identifierForVendor.UUIDString);
    
    [super viewDidLoad];
    self.blueManager = CBluetoothManager::instance();
    //初始化数组，表示图
    peripheralArr = [[NSMutableArray alloc]initWithCapacity:10];
    
    tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 320, 200)];
    tableview.dataSource = self;
    tableview.delegate = self;
    [self.view addSubview:tableview];
    
    _data = [[NSMutableData alloc] init];

    dispatch_async(dispatch_get_global_queue(0, 0),
    ^{
        self.blueManager->searchBlueDevice(peripheralArr);
        [self.tableview performSelector:@selector(reloadData) onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO];

    });
    //更新表格

}


-(void)dealloc
{
    [super dealloc];
    delete self.blueManager;
    self.blueManager = nil;
}


#pragma mark--------UITableView Delegate



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (peripheralArr.count != 0)
    {
        return peripheralArr.count;
    }else
    {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"TableviewCell_Identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if (peripheralArr.count) {
        CBPeripheral *peri = [peripheralArr objectAtIndex:indexPath.row];
        cell.textLabel.text = peri.name;
        return cell;
    }else{
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    connectPeripheral = (CBPeripheral *)[peripheralArr objectAtIndex:indexPath.row];
    
    
    NSString *password = @"000000";
    
    [self connectBluetoothWithPassword:password andCBPeripheral:connectPeripheral];
    
    
//    //普通方式连接
////    NSString *str = [NSString stringWithFormat:@"%p",connectPeripheral];
////    self.blueManager->connect((char *)str.UTF8String, 0, 0);
//    
//    
//    //PullSDK方式连接
//    //NSString *str = [NSString stringWithFormat:@"protocol=BLUETOOTH,address=%p,timeout=2000,passwd=\n\n%@",connectPeripheral,@"5888128791A2488B8C2788A2E34E0C2F"];
//    
//    //NSString *str = [NSString stringWithFormat:@"protocol=BLUETOOTH,address=%p,timeout=2000,passwd=\n1234567890",connectPeripheral];
//    
//    NSString *str = [NSString stringWithFormat:@"protocol=BLUETOOTH,address=%p,timeout=2000,passwd=12312124234\n%@\n",connectPeripheral,[UIDevice currentDevice].identifierForVendor.UUIDString];
//
//    
//    const char *para = [str UTF8String];
//
//    
//    
//    
//    handle = PullSDKConnect(para);
//    if (handle != NULL) {
//        NSLog(@"Connect OKAY\n");
//        //判断用户权限
//        //用于存储数据的buffer
//        char paraBuffer[512] = {0};
//        NSString *str = @"UserType";
//        const char *userType = [str UTF8String];
//        int ret = PullSDKGetDeviceParam(handle, paraBuffer, sizeof(paraBuffer), userType);
//        NSLog(@"ret==========[%d]\n bufff==============[%s]",ret,paraBuffer);
//        
//        //获取mac地址
//        self.blueManager->requestMacAddr();
//        
//        //普通方式读取mac地址
//        char buffer[512] = {0};
//        int retCount = self.blueManager->readMacAddr(buffer, 0, sizeof(buffer));
//        if (retCount != -1)
//        {
//            NSData * retData = [NSData dataWithBytes:buffer length:retCount];
////            NSLog(@"macAdress ==== [%@]\n",retData);
//            NSString *str = [retData dataToByteTohexStr];
//            if (str.length != 0 && str !=nil) {
//                //存入缓存
//            }
//            else  //弹出提示框，同时断开连接从新搜索
//            {
//                
//            }
//            NSLog(@"macAdress ===============[%@]",str);
//
//        }
//    }
//    
    


}



#pragma mark ---------Connect  Bluetooth
-(void)connectBluetoothWithPassword:(NSString *)password andCBPeripheral:(CBPeripheral *)cbPer
{
//    //TODO:出现菊花，并连接指定的蓝牙
//    HUD.labelText = @"连接中...";
//    [HUD show:YES];
    
    /*
     1.蓝牙层连接，并发送配对密码
     成功：获取mac地址并存入缓存，而后进行pull层连接
     失败：断开连接，同时从新搜索设备，并提示用户
     2.pull层连接
     成功：判断本地缓存内是否存在蓝牙锁对应的数据库，拉取表结构
     失败：断开连接，同时从新搜索设备，并提示用户
     3.数据库的创建
     若没有数据库，则创建，并创建对应的表
     */
    
    
    //1.蓝牙层连接，并发送配对密码
    //连接蓝牙
    NSString *str = [NSString stringWithFormat:@"%p",connectPeripheral];
    int connectRetcount = self.blueManager->connect((char *)str.UTF8String, 0, 0);
    if (connectRetcount != -1)//连接成功
    {
        //发送配对密码
        NSString *passwordStr = [NSString stringWithFormat:@"AT+PASSKEY=%@",password];
        NSData *data = [passwordStr stringToHexStringToByteToNSDataForCharacteristic2];
        char *datebyte = (char *)data.bytes;
        int requestRetcount = self.blueManager->requestMacAddr(datebyte, 0, data.length);
        if (requestRetcount != -1)//配对密码写入完成
        {
            char buffer[512] = {0};
            int readMacRetCount = self.blueManager->readMacAddr(buffer, 0, sizeof(buffer));
            if (readMacRetCount == -1)//配对失败
            {
                [peripheralArr removeAllObjects];
                [tableview reloadData];
                UIAlertView *conncectFailAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"连接失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                conncectFailAlert.tag = 24;
                [conncectFailAlert show];
            }else//配对成功
            {
                self.blueManager->logBlueTooth();
                NSString *pullPara = [NSString stringWithFormat:@"protocol=BLUETOOTH,address=,timeout=2000,passwd=12312124234\n%@\n",[UIDevice currentDevice].identifierForVendor.UUIDString];
                const char *para = [pullPara UTF8String];
                self.blueManager->logBlueTooth();
                handle = PullSDKConnect(para);
                self.blueManager->logBlueTooth();
                

                if (handle != NULL)//pull层连接成功
                {
                    //普通方式读取mac地址
                    //发送获取mac地址指令
                    NSString *getMacAddress = @"41542B4C414444520D0A";
                    NSData *getMacData = [getMacAddress hexToByteToNSData];
                    char *getMacByte = (char *)getMacData.bytes;
                    self.blueManager->requestMacAddr(getMacByte, 0, getMacData.length);
                    //读取返回的mac地址
                    char buffer[512] = {0};
                    int retCount = self.blueManager->readMacAddr(buffer, 0, sizeof(buffer));

                    if (retCount != -1)
                    {
                        //获取mac地址成功
                        NSData * retData = [NSData dataWithBytes:buffer length:retCount];
                        NSString *str = [retData dataToByteTohexStr];
                        NSLog(@"%@",str);
                        
                        //PullSDK拉取表结构
                        char buffer[4096] = {0};
                        int i = PullSDKGetTableStruct(handle,buffer,sizeof(buffer));
                        if (!i)//表结构拉取成功
                        {
                            NSString *dateStr = [[NSString alloc]initWithCString:(const char *)buffer encoding:NSASCIIStringEncoding];
                            NSLog(@"%@",dateStr);
                        }
                    }
                    else//获取mac地址失败
                    {
                        UIAlertView *alertMac = [[UIAlertView alloc]initWithTitle:@"提示" message:@"获取mac地址失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        alertMac.tag = 25;
                        [alertMac show];
                    }
  
            }
            
        }
    }
    }
}








//拉取用户数据
-(IBAction)AA02:(id)sender
{
//    //PullSDK开门
//    int i = PullSDKControlDevice(handle, 1, 1, 0, 5, 0,NULL);
//    NSLog(@"%d",i);
    
    
    char buffer[5120] = {0};
    NSString *tableN = @"transaction";
    const char *TableName = [tableN UTF8String];
    NSString *fieldN = @"*";
    const char *fieldName = [fieldN UTF8String];
    NSString *nilstr = @"";
    const char *nilStr = [nilstr UTF8String];
    NSString *oneStr = @"";
    const char *one = [oneStr UTF8String];
    int ret = 1;
    do
    {

        //拉取全部数据
       ret =  PullSDKGetDeviceData(handle, buffer,sizeof(buffer), TableName, fieldName, nilStr, one);
        
        NSLog(@"buffer========【%s】",buffer);
        //解析数据

    } while (ret != 0);
//    i = PullSDKGetDeviceDataCount(handle, TableName, fieldName, nilStr);
//    NSLog(@"PullSDKGetDeviceDataCount result========[%d]",i);

    
//    NSString *str = @"AA0105040001010005057755";
//    NSData *data = [str hexToByteToNSData];
//    char *datebyte = (char *)data.bytes;
//    self.blueManager->write(datebyte, 0, data.length);

    
//    //普通方式请求mac地址
//    self.blueManager->requestMacAddr();
}



//拉取表结构
- (IBAction)openTheDoor:(id)sender
{


}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)readData:(id)sender
{
    
//    //普通方式读取mac地址
//    char buffer[512] = {0};
//    int retCount = self.blueManager->readMacAddr(buffer, 0, sizeof(buffer));
//    if (retCount != -1)
//    {
//        NSData * retData = [NSData dataWithBytes:buffer length:retCount];
//        
//        NSLog(@"readbuffer ==== [%@]\n",retData);
//        NSString *str = [retData dataToByteTohexStr];
//        NSLog(@"%@",str);
//    }
    

    
    
//    char buffer[512] = {0};
//    int retCount = self.blueManager->read(buffer, 0, sizeof(buffer));
//    if (retCount != -1) {
//        NSData * retData = [NSData dataWithBytes:buffer length:retCount];
//        
//        NSLog(@"readbuffer ==== [%@]\n",retData);
//    }
    
}

-(IBAction)disconnectBle:(id)sender
{
    self.blueManager->disconnect();
    [peripheralArr removeAllObjects];
    [self.tableview reloadData];
    dispatch_async(dispatch_get_global_queue(0, 0),
                   ^{
                       
                       self.blueManager->searchBlueDevice(peripheralArr);
                       dispatch_async(dispatch_get_main_queue(), ^{
                           [self.tableview reloadData];
                       });
                   });
    
}

@end






